@echo off
setlocal enabledelayedexpansion

cd /d "%~dp0"

set "APP_PORT=:8111"
set "APP_DEBUG=true"
set "DB_PATH=data.db"
set "JWT_SECRET="

if exist ".env" (
  for /f "usebackq tokens=1,* delims== eol=#" %%A in (".env") do (
    if /I "%%A"=="APP_PORT" set "APP_PORT=%%B"
    if /I "%%A"=="APP_DEBUG" set "APP_DEBUG=%%B"
    if /I "%%A"=="DB_PATH" set "DB_PATH=%%B"
    if /I "%%A"=="JWT_SECRET" set "JWT_SECRET=%%B"
  )
)

:parse_args
if "%~1"=="" goto after_args

if /I "%~1"=="--port" (
  if "%~2"=="" goto usage
  set "APP_PORT=%~2"
  shift & shift
  goto parse_args
)

if /I "%~1"=="--debug" (
  if "%~2"=="" goto usage
  set "APP_DEBUG=%~2"
  shift & shift
  goto parse_args
)

if /I "%~1"=="--db" (
  if "%~2"=="" goto usage
  set "DB_PATH=%~2"
  shift & shift
  goto parse_args
)

if /I "%~1"=="--db-path" (
  if "%~2"=="" goto usage
  set "DB_PATH=%~2"
  shift & shift
  goto parse_args
)

if /I "%~1"=="--jwt-secret" (
  if "%~2"=="" goto usage
  set "JWT_SECRET=%~2"
  shift & shift
  goto parse_args
)

if /I "%~1"=="-h" (
  goto usage
)

if /I "%~1"=="--help" (
  goto usage
)

echo Unknown option: %~1
goto usage

:usage
echo Usage: %~nx0 [--port ^<port^>] [--debug ^<true^|false^>] [--db ^<db_path^>] [--jwt-secret ^<secret^>]
echo.
echo Examples:
echo   %~nx0 --port :8111 --debug true --db data.db --jwt-secret mysecret
exit /b 1

:after_args

if "%JWT_SECRET%"=="" (
  echo Warning: JWT secret not specified, using value from database or default config.
)

echo Building ob-share-server.exe...
go build -o ob-share-server.exe main.go
if errorlevel 1 (
  echo Build failed.
  exit /b 1
)

echo Starting ob-share-server on port %APP_PORT% (debug=%APP_DEBUG%, db=%DB_PATH%)...
set "APP_PORT=%APP_PORT%"
set "APP_DEBUG=%APP_DEBUG%"
set "DB_PATH=%DB_PATH%"
set "JWT_SECRET=%JWT_SECRET%"

APP_PORT=%APP_PORT% ^
APP_DEBUG=%APP_DEBUG% ^
DB_PATH=%DB_PATH% ^
JWT_SECRET=%JWT_SECRET% ^
ob-share-server.exe

endlocal
